import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';
import VueRouter from 'vue-router';
import routes from '@/router/routes';
import '@/css/reset.css'

import VueMarkdownEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import vuepressTheme from '@kangc/v-md-editor/lib/theme/vuepress';
import '@kangc/v-md-editor/lib/theme/style/vuepress.css';
import Prism from 'prismjs';

import VMdPreview from '@kangc/v-md-editor/lib/preview';
import '@kangc/v-md-editor/lib/style/preview.css';
// 引入你所使用的主题 此处以 github 主题为例
import githubTheme from '@kangc/v-md-editor/lib/theme/github';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import hljs from 'highlight.js';

import store from './store/index';

Vue.use(ElementUI);
Vue.use(VueRouter);
Vue.use(VueMarkdownEditor);
Vue.use(VMdPreview);

VMdPreview.use(githubTheme, {
  Hljs: hljs,
});

VueMarkdownEditor.use(vuepressTheme, {
  Prism,
});

const router = new VueRouter({
  routes,
})

import nprogress from 'nprogress'
//引入进度条样式
import 'nprogress/nprogress.css'
nprogress.configure({ showSpinner: false })

//全局守卫:项目当中任意路由切换都会触发的钩子
//全局前置守卫
router.beforeEach(async (to, _from, next) => {
  //to:你将要访问那个路由
  //from:你从来个路由而来
  //next:路由的放行函数
  nprogress.start()
  //获取token,去判断用户登录、还是未登录
  const token = localStorage.getItem('token')
  const username = localStorage.getItem('username')
  //用户登录判断
  if (token) {
    //登录成功,访问login,不能访问,指向首页
    if (to.path == '/userLogin') {
      next({ path: '/' })
    } else {
      //登录成功访问其余六个路由(登录排除)
      //有用户信息
      if (username) {
        // 获取store中的数据
        const userData = store.state.userData;
        if (!userData) {
          store.dispatch('fetchUserData');
        }
        //放行
        next()
      } else {
        // 调用store中的函数
        localStorage.clear()
        next({ path: '/userLogin', query: { redirect: to.path } })
      }
    }
  } else {
    //用户未登录判断
    if (to.path == '/userLogin' || to.path == '/userRegister') {
      next()
    } else {
      next({ path: '/userLogin', query: { redirect: to.path } })
    }
  }
})
//全局后置守卫
router.afterEach(() => {
  nprogress.done()
})

new Vue({
  router,
  store,
  el: '#app',
  render: h => h(App)
});

// import Vue from 'vue'
// import App from './App.vue'

// Vue.config.productionTip = false

// new Vue({
//   render: h => h(App),
// }).$mount('#app')